/**
 * 权限声明：
 */
package com.handy.webwork.action.result;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.handy.webwork.action.AbstractAction;

/**
 * 默认视图输出，jsp,html,htm
 * 
 * @author rocken.zeng@gmail.com
 * 
 */
public class StaticFile {
	private static Log log = LogFactory.getLog(StaticFile.class);

	private HttpServletRequest request;
	private HttpServletResponse response;
	private ServletContext context;

	public StaticFile(HttpServletRequest request, HttpServletResponse response,ServletContext context) {
		this.request = request;
		this.response = response;
		this.context = context;
		if (log.isDebugEnabled()){
			log.info("视图：静态文件输出。");
		}		
	}

	/**
	 * 当result类型为空时，跳转到下个指定的页面。request范围内的数据共享。
	 * 
	 * @param action
	 * @param resultValue
	 * @throws IOException
	 * @throws ServletException 
	 */
	@SuppressWarnings("unchecked")
	public void doStaticFile(AbstractAction action){
		String fileName = null;
		HashMap _root = action.sendData();
		if (null!=_root && null!=_root.get(AbstractAction.HANDY_STATIC_FILE)){
			fileName = (String)_root.get(AbstractAction.HANDY_STATIC_FILE);
		}
		
		if (null == fileName || "".equals(fileName)){
			String error = "当action返回一个静态文件时，action.sendData().get(AbstractAction.HANDY_STATIC_FILE)方法一定要返回一个可用的文件（正确的路径和名称）";
			log.error(error);
			try {
				response.getWriter().println();
			} catch (IOException e) {
				log.error(e.getMessage());
			}finally{
				try {
					response.getWriter().close();
				} catch (IOException e) {
					log.error(e.getMessage());
				}	
			}
			
			return;
		}
		
		//当没有指定result类型时让容器处理视图。
		String url = fileName;
		if (!url.startsWith("/")) {
			url = "/" + url.trim();
		}
		if (log.isDebugEnabled()){
			log.debug("forward to file: " +url);
		}
		RequestDispatcher rd = context.getRequestDispatcher(url);
//		log.info("url="+url);
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			log.error(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
}
